package com.phei.netty.chat3;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

public class SecureChatServer extends ChatServer {
	
	private SslContext context;
	
	public SecureChatServer(SslContext context) {
		this.context = context;
	}
	
	@Override
	public  ChannelInitializer<Channel> createInitializer(ChannelGroup group){
		return new SecureChatServerInitializer(group, context,false);
		
	}
	public static void main(String[] args) {
		try {
			SelfSignedCertificate cert = new SelfSignedCertificate();
			SslContext context =  SslContextBuilder.forServer(cert.certificate(), cert.privateKey()).build();
			/*KeyStore ks = KeyStore.getInstance("JKS");
			InputStream ksInputStream = new FileInputStream("D:\\demo\\test.jks");
			ks.load(ksInputStream, "123456".toCharArray());
			KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			kmf.init(ks, "123456".toCharArray());
			SSLContext context = SSLContext.getInstance("TLS");
			context.init(kmf.getKeyManagers(), null, null);*/
			
			SecureChatServer endpoint  =  new SecureChatServer(context);
			ChannelFuture future =  endpoint.start(new InetSocketAddress(8989));
			Runtime.getRuntime().addShutdownHook(new Thread() {
				public void run() {
					endpoint.destroy();
				}
			});
			
			future.channel().closeFuture().syncUninterruptibly();
		} catch (IOException | CertificateException  e) {
			e.printStackTrace();
		}
		
	}
	
	
}
